﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using Cofe.Core;
using Newtonsoft.Json;

namespace Cofe.Web.Utils
{
    public class XmlToJsonSerializerFormatter : MediaTypeFormatter
    {
        #region Constructor

        public XmlToJsonSerializerFormatter(Type[] knownTypes)
        {
            SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
            _supportedTypes = knownTypes;            
        }

        #endregion

        #region Methods

        public override bool CanWriteType(Type type)
        {
            if (_supportedTypes.Contains(type))            
                return true;
            return false;
        }

        public override bool CanReadType(Type type)
        {
            if (_supportedTypes.Contains(type))
                return true;
            return false;
        }


        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream,
            HttpContent content, TransportContext transportContext)
        {            
            var serializer = new DataContractSerializer(type, _supportedTypes);
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, value);
            ms.Seek(0, SeekOrigin.Begin);
            
            XmlDocument doc = new XmlDocument();
            doc.Load(ms);

            string jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented, true);
            using (var sw = new StreamWriter(writeStream))
                await sw.WriteAsync(jsonText);
            
        }

        public override Task<object> ReadFromStreamAsync(Type type, System.IO.Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
        }

        #endregion

        #region Data

        Type[] _supportedTypes;      

        #endregion

        #region Public Properties
        

        #endregion



    }
}